﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using HZ.Supervise.Model;
using System.Text;
using HZ.Supervise.IBLL;
using HZ.Supervise.Model.Enum;

namespace HZ.Supervise.Web.Secondphase.ReportArea
{
	public partial class ProcureArea : BasePage
	{
		string strAreaId = string.Empty;
        string sortSource = "''";

        public ProcureArea()
        {
            this.ModuleNo = Module.趋势走向.ToString();
            this.PageOperateType = OperateType.县区排名.ToString();
        }
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				HZ.Supervise.Model.User user = CurrentAccount.GetUser();

				AreaControls1.InitAreaID = user.Org.Area.AreaID;


				strAreaId = CurrentAccount.GetUser().Org.Area.AreaID;
				this.MaxforMonth1.Banding();
				Databing();
			}
		}

		private void Databing()
		{

			StringBuilder sbCurrentMonth = new StringBuilder();

			sbCurrentMonth = HZ.Supervise.Web.Function.GetConditionOfAreaId(sbCurrentMonth, this.AreaControls1.SelectedAreaID) as StringBuilder;

			sbCurrentMonth.AppendFormat("   AND daytime='{0}'", this.MaxforMonth1.Getvalue());

			StringBuilder sbLastMonth = new StringBuilder();

			sbLastMonth = HZ.Supervise.Web.Function.GetConditionOfAreaId(sbLastMonth, this.AreaControls1.SelectedAreaID) as StringBuilder;

			string _oldYearmonth = this.MaxforMonth1.Getvalue().Insert(4, "-") + "-01";//根据本月拼接字符串，以便于能够转化成datetime类型，从而能够调用datetime类中求得上个月的方法

			sbLastMonth.AppendFormat("  AND daytime='{0}'", Convert.ToDateTime(_oldYearmonth).AddMonths(-1).ToString("yyyyMM"));

			//string sortSource = "2";

            //if (this.dropMort.SelectedValue == "0" || this.dropMort.SelectedValue == "1" || this.dropMort.SelectedValue == "2")
            //{

            //    sbCurrentMonth.AppendFormat(" and SortSorce = {0}", this.dropMort.SelectedValue);

            //    sbLastMonth.AppendFormat(" and SortSorce = {0}", this.dropMort.SelectedValue);

            //    sortSource = this.dropMort.SelectedValue;

            //}

			string orderOfrank = "";

			string orderBy = "";

			if (this.ddlorderby.SelectedValue == "PurchaseAmount" || this.ddlorderby.SelectedValue == "DistributeAmount" || this.ddlorderby.SelectedValue == "WareHouseAmount")
			{

				orderOfrank = " sum(" + this.ddlorderby.SelectedValue + ")";

				orderBy = this.ddlorderby.SelectedValue + "total  " + this.dropOrder.SelectedValue;

			}
			else
			{

				if (this.ddlorderby.SelectedValue == "WareHouseRate")
				{
                    orderOfrank = " (case when SUM(WarehouseAmount) = 0 then 0 when SUM(PurchaseAmount)=0 then 0 when CONVERT(decimal(18,3),CONVERT(float, SUM(WarehouseAmount)) / SUM(PurchaseAmount))>1 then 1 else  CONVERT(decimal(18,3),CONVERT(float, SUM(WarehouseAmount)) / SUM(PurchaseAmount)) end)";
				}
				else
				{

                    orderOfrank = " (case when SUM(DistributeAmount) = 0 then 0 when SUM(PurchaseAmount)=0 then 0 when CONVERT(decimal(18,3),CONVERT(float, SUM(DistributeAmount)) / SUM(PurchaseAmount))>1 then 1 else CONVERT(decimal(18,3),CONVERT(float, SUM(DistributeAmount)) / SUM(PurchaseAmount)) end)";

				}

				orderBy = this.ddlorderby.SelectedValue + " " + this.dropOrder.SelectedValue;

			}

			int totalrecord = 0;

			IBLL_Area entity = BLLFactory.IBLL_Area();

            DataTable dt = entity.GetProcureAreaMax1(orderOfrank, orderBy, sbCurrentMonth.ToString(), sbLastMonth.ToString(), sortSource, this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out totalrecord);

            //HZ.Supervise.Web.Function.ChangeRate(dt, "DistributeRate", "addDistributeRate");

            //HZ.Supervise.Web.Function.ChangeRate(dt, "WareHouseRate", "addWareHouseRate");

			Function.AddColRank(dt, "pms");

            //Function.AddColumn(dt, "SortSorce");

			this.AspNetPager1.RecordCount = totalrecord;

			this.gvwProcureCatalog.DataSource = dt;

			this.gvwProcureCatalog.DataBind();

		}


        //private void Binds(string sqlnewwhere, string sqloldwhere, string orderwhere, string sqlArea)
        //{
        //    DataSet ds = HZ.Supervise.BLLFactory.IBLL_Area().GetProcureAreaMax(sqlnewwhere, sqloldwhere, orderwhere, sqlArea.ToString());

        //    if (ds.Tables.Count == 2)
        //    {
        //        DataTable dtNewData = ds.Tables[0];//本月数据
        //        DataTable dtOldData = ds.Tables[1];//上个月数据

        //        DataColumn column = new DataColumn();
        //        column.DataType = System.Type.GetType("System.Int32");
        //        column.ColumnName = "oldId";
        //        dtNewData.Columns.Add(column);

        //        DataColumn columnIsjy = new DataColumn();
        //        columnIsjy.DataType = System.Type.GetType("System.String");
        //        columnIsjy.ColumnName = "IsDrug";
        //        dtNewData.Columns.Add(columnIsjy);



        //        if (dtNewData.Rows.Count > 0)
        //        {

        //            foreach (DataRow row in dtNewData.Rows)
        //            {
        //                int i = 0;
        //                foreach (DataRow rowOld in dtOldData.Rows)
        //                {
        //                    if (row["AreaName"].ToString().Equals(rowOld["AreaName"].ToString()))
        //                    {
        //                        row["oldId"] = rowOld["id"].ToString();
        //                        i++;
        //                        break;
        //                    }
        //                }

        //                //if (this.dropMort.Items.Count > 0) { row["IsDrug"] = this.dropMort.SelectedItem.Text.Trim(); }

        //                if (i == 0)
        //                {
        //                    row["oldId"] = 0;
        //                }
        //            }
        //        }


        //        Function.ChangeRate(dtNewData, "DistributeRate", "addDistributeRate");
        //        Function.ChangeRate(dtNewData, "WareHouseRate", "addWareHouseRate");
        //        Function.AddColRank(dtNewData, "oldId");
        //        this.gvwProcureCatalog.DataSource = dtNewData;
        //        this.gvwProcureCatalog.DataBind();


        //    }
        //    else
        //    {

        //    }
        //}

		protected void btnQuery_Click(object sender, EventArgs e)
		{

			this.AspNetPager1.CurrentPageIndex = 1;

		}

		protected void lbnSwitch_Click(object sender, EventArgs e)
		{

		}

		protected void btnExcel_Click(object sender, EventArgs e)
		{
			StringBuilder sbCurrentMonth = new StringBuilder();

			sbCurrentMonth = HZ.Supervise.Web.Function.GetConditionOfAreaId(sbCurrentMonth, this.AreaControls1.SelectedAreaID) as StringBuilder;

			sbCurrentMonth.AppendFormat("   AND daytime='{0}'", this.MaxforMonth1.Getvalue());

			StringBuilder sbLastMonth = new StringBuilder();

			sbLastMonth = HZ.Supervise.Web.Function.GetConditionOfAreaId(sbLastMonth, this.AreaControls1.SelectedAreaID) as StringBuilder;

			string _oldYearmonth = this.MaxforMonth1.Getvalue().Insert(4, "-") + "-01";//根据本月拼接字符串，以便于能够转化成datetime类型，从而能够调用datetime类中求得上个月的方法

			sbLastMonth.AppendFormat("  AND daytime='{0}'", Convert.ToDateTime(_oldYearmonth).AddMonths(-1).ToString("yyyyMM"));

            //if (this.dropMort.SelectedValue == "0" || this.dropMort.SelectedValue == "1" || this.dropMort.SelectedValue == "2")
            //{

            //    sbCurrentMonth.AppendFormat(" and SortSorce = {0}", this.dropMort.SelectedValue);

            //    sbLastMonth.AppendFormat(" and SortSorce = {0}", this.dropMort.SelectedValue);

            //    sortSource = this.dropMort.SelectedValue;

            //}

			string orderOfrank = "";

			string orderBy = "";

			if (this.ddlorderby.SelectedValue == "PurchaseAmount" || this.ddlorderby.SelectedValue == "DistributeAmount" || this.ddlorderby.SelectedValue == "WareHouseAmount")
			{

				orderOfrank = " sum(" + this.ddlorderby.SelectedValue + ")";

				orderBy = this.ddlorderby.SelectedValue + "total  " + this.dropOrder.SelectedValue;

			}
			else
			{

				if (this.ddlorderby.SelectedValue == "WareHouseRate")
				{
                    orderOfrank = " (case when SUM(WarehouseAmount) = 0 then 0 when SUM(PurchaseAmount)=0 then 0 when CONVERT(decimal(18,3),CONVERT(float, SUM(WarehouseAmount)) / SUM(PurchaseAmount))>1 then 1 else  CONVERT(decimal(18,3),CONVERT(float, SUM(WarehouseAmount)) / SUM(PurchaseAmount)) end)";
				}
				else
				{

                    orderOfrank = " (case when SUM(DistributeAmount) = 0 then 0 when SUM(PurchaseAmount)=0 then 0 when CONVERT(decimal(18,3),CONVERT(float, SUM(DistributeAmount)) / SUM(PurchaseAmount))>1 then 1 else CONVERT(decimal(18,3),CONVERT(float, SUM(DistributeAmount)) / SUM(PurchaseAmount)) end)";

				}

				orderBy = this.ddlorderby.SelectedValue + " " + this.dropOrder.SelectedValue;

			}

			int totalrecord = 0;

			IBLL_Area entity = BLLFactory.IBLL_Area();

			DataTable dt = entity.GetProcureAreaMax1(orderOfrank, orderBy, sbCurrentMonth.ToString(), sbLastMonth.ToString(), sortSource, 1, 0, out totalrecord);

            //HZ.Supervise.Web.Function.ChangeRate(dt, "DistributeRate", "addDistributeRate");

            //HZ.Supervise.Web.Function.ChangeRate(dt, "WareHouseRate", "addWareHouseRate");

			Function.AddColRank(dt, "pms");

            //Function.AddColumn(dt, "SortSorce");

			HZ.Excel.ExcelHelper.ExportDataForWeb(dt, this.gvwProcureCatalog);

		}

		protected void gvwProcureCatalog_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				Label lab = (Label)e.Row.FindControl("labid");
				if (lab != null)
				{
					if (lab.Text.Trim() == "2147483647")
					{
						lab.Text = "上月无排名";
					}
				}

                //e.Row.Cells[0].Text = HZ.Supervise.Web.Function.GetCityNameByCountryName(e.Row.Cells[0].Text);
                e.Row.Cells[0].Text = e.Row.Cells[0].Text;
			}
		}

		private string GetPrevious(string _YearMoth)
		{
			if (string.IsNullOrEmpty(_YearMoth))
			{
				return null;
			}
			if (!HZ.Fun.IsInt(_YearMoth))
			{
				return null;
			}

			string strSub = _YearMoth.Substring(_YearMoth.Length - 2, 2);

			int PreviousYearMoth;

			if (strSub == "01")
			{
				PreviousYearMoth = int.Parse(_YearMoth) - 2;

				PreviousYearMoth = int.Parse(PreviousYearMoth.ToString().Replace("999", "912"));
			}
			else
			{
				PreviousYearMoth = int.Parse(_YearMoth) - 1;
			}


			return PreviousYearMoth.ToString();
		}

		protected void AspNetPager1_PageChanged(Object sender, EventArgs e)
		{

			this.Databing();

		}
	}
}
